/**
 * 字体加载优化工具
 * @author Wu.Liang
 * @date 2025-01-30
 * @description 解决字体加载缓慢问题，提供字体加载状态管理
 */

/**
 * 字体加载器类
 */
class FontLoader {
  constructor() {
    this.loadedFonts = new Set()
    this.loadingFonts = new Set()
    this.failedFonts = new Set()
    this.callbacks = new Map()
  }

  /**
   * 预加载字体
   * @param {string} fontFamily 字体族名
   * @param {string} fontUrl 字体URL
   * @param {Function} callback 加载完成回调
   */
  async preloadFont(fontFamily, fontUrl, callback) {
    if (this.loadedFonts.has(fontFamily)) {
      callback && callback(true)
      return Promise.resolve(true)
    }

    if (this.loadingFonts.has(fontFamily)) {
      // 如果正在加载，添加回调
      if (!this.callbacks.has(fontFamily)) {
        this.callbacks.set(fontFamily, [])
      }
      this.callbacks.get(fontFamily).push(callback)
      return Promise.resolve(false)
    }

    this.loadingFonts.add(fontFamily)

    try {
      // 使用FontFace API加载字体
      if ('FontFace' in window) {
        const fontFace = new FontFace(fontFamily, `url(${fontUrl})`)
        await fontFace.load()
        document.fonts.add(fontFace)
      } else {
        // 降级方案：使用link标签预加载
        await this.preloadWithLink(fontUrl)
      }

      this.loadedFonts.add(fontFamily)
      this.loadingFonts.delete(fontFamily)
      
      // 执行回调
      callback && callback(true)
      this.executeCallbacks(fontFamily, true)
      
      return true
    } catch (error) {
      console.warn(`字体加载失败: ${fontFamily}`, error)
      this.failedFonts.add(fontFamily)
      this.loadingFonts.delete(fontFamily)
      
      // 执行回调
      callback && callback(false)
      this.executeCallbacks(fontFamily, false)
      
      return false
    }
  }

  /**
   * 使用link标签预加载字体
   * @param {string} fontUrl 字体URL
   */
  preloadWithLink(fontUrl) {
    return new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'preload'
      link.as = 'font'
      link.type = 'font/ttf'
      link.crossOrigin = 'anonymous'
      link.href = fontUrl
      
      link.onload = () => resolve()
      link.onerror = () => reject(new Error('字体加载失败'))
      
      document.head.appendChild(link)
    })
  }

  /**
   * 执行字体加载回调
   * @param {string} fontFamily 字体族名
   * @param {boolean} success 是否成功
   */
  executeCallbacks(fontFamily, success) {
    const callbacks = this.callbacks.get(fontFamily)
    if (callbacks) {
      callbacks.forEach(callback => callback(success))
      this.callbacks.delete(fontFamily)
    }
  }

  /**
   * 检查字体是否已加载
   * @param {string} fontFamily 字体族名
   */
  isFontLoaded(fontFamily) {
    return this.loadedFonts.has(fontFamily)
  }

  /**
   * 检查字体是否加载失败
   * @param {string} fontFamily 字体族名
   */
  isFontFailed(fontFamily) {
    return this.failedFonts.has(fontFamily)
  }

  /**
   * 获取字体加载状态
   * @param {string} fontFamily 字体族名
   */
  getFontStatus(fontFamily) {
    if (this.loadedFonts.has(fontFamily)) return 'loaded'
    if (this.failedFonts.has(fontFamily)) return 'failed'
    if (this.loadingFonts.has(fontFamily)) return 'loading'
    return 'pending'
  }
}

// 创建全局字体加载器实例
const fontLoader = new FontLoader()

/**
 * 预加载iconfont字体
 */
export async function preloadIconFont() {
  const fontFamily = 'iconfont'
  const fontUrl = 'https://at.alicdn.com/t/font_2225171_8kdcwk4po24.ttf'
  
  try {
    const success = await fontLoader.preloadFont(fontFamily, fontUrl, (loaded) => {
      if (loaded) {
        console.log('iconfont字体加载成功')
        // 添加加载成功的类名
        document.documentElement.classList.add('iconfont-loaded')
        document.documentElement.classList.remove('iconfont-loading')
      } else {
        console.warn('iconfont字体加载失败，使用系统字体')
        document.documentElement.classList.add('iconfont-failed')
        document.documentElement.classList.remove('iconfont-loading')
      }
    })
    
    return success
  } catch (error) {
    console.error('字体预加载失败:', error)
    document.documentElement.classList.add('iconfont-failed')
    document.documentElement.classList.remove('iconfont-loading')
    return false
  }
}

/**
 * 检查字体加载状态
 */
export function checkFontStatus() {
  const status = fontLoader.getFontStatus('iconfont')
  console.log('iconfont字体状态:', status)
  return status
}

/**
 * 字体加载优化初始化
 */
export function initFontOptimization() {
  // 添加加载中的类名
  document.documentElement.classList.add('iconfont-loading')
  
  // 预加载字体
  preloadIconFont()
  
  // 设置超时处理
  setTimeout(() => {
    if (fontLoader.getFontStatus('iconfont') === 'loading') {
      console.warn('字体加载超时，使用系统字体')
      document.documentElement.classList.add('iconfont-timeout')
      document.documentElement.classList.remove('iconfont-loading')
    }
  }, 5000) // 5秒超时
}

/**
 * 字体显示优化
 */
export function optimizeFontDisplay() {
  // 添加字体优化类
  document.documentElement.classList.add('font-optimized')
  
  // 监听字体加载完成
  if ('fonts' in document) {
    document.fonts.ready.then(() => {
      console.log('所有字体加载完成')
      document.documentElement.classList.add('fonts-ready')
    })
  }
}

export default fontLoader
